import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import { mockData } from '../utils/mockData';

const IncidentAreaStats = () => {
  const chartRef = useRef(null);
  const chartInstance = useRef(null);
  const scrollIntervalRef = useRef(null);
  const startIndexRef = useRef(0);
  const sortedBureausRef = useRef([]);
  const sortedDataRef = useRef([]);

  useEffect(() => {
    if (chartRef.current) {
      chartInstance.current = echarts.init(chartRef.current);
      updateChart();
      setupAutoScroll();
    }

    const handleResize = () => {
      if (chartInstance.current) {
        chartInstance.current.resize();
      }
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      if (chartInstance.current) {
        chartInstance.current.dispose();
      }
      if (scrollIntervalRef.current) {
        clearInterval(scrollIntervalRef.current);
      }
    };
  }, []);

  const updateChart = () => {
    const result = mockData.incidentArea;
    const bureaus = [];
    const data = [];

    result.forEach((item) => {
      bureaus.push(item.calculate_time);
      data.push(parseInt(item.area_work_order_count));
    });

    const sortedIdxs = data
      .map((val, idx) => ({ val, idx }))
      .sort((a, b) => b.val - a.val)
      .map((item) => item.idx);

    sortedBureausRef.current = sortedIdxs.map((idx) => bureaus[idx]);
    sortedDataRef.current = sortedIdxs.map((idx) => data[idx]);

    const option = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
        formatter: function (params) {
          const data = params[0];
          return `${data.name}: ${data.value || 0} 次`;
        },
        backgroundColor: "rgba(6, 33, 68, 0.9)",
        borderColor: "#24bbec",
        textStyle: {
          color: "#fff",
        },
      },
      grid: {
        left: "5%",
        right: "5%",
        bottom: "10%",
        top: "5%",
        containLabel: true,
      },
      xAxis: {
        type: "value",
        name: "工单数量",
        nameLocation: "end",
        nameTextStyle: {
          color: "#a2d3e8",
        },
        axisLine: {
          lineStyle: {
            color: "rgba(162, 211, 232, 0.5)",
          },
        },
        axisLabel: {
          color: "#a2d3e8",
          fontSize: 20,
        },
        splitLine: {
          lineStyle: {
            color: "rgba(162, 211, 232, 0.1)",
          },
        },
      },
      yAxis: {
        type: "category",
        data: sortedBureausRef.current,
        axisLine: {
          lineStyle: {
            color: "rgba(162, 211, 232, 0.5)",
          },
        },
        axisLabel: {
          color: "#e6f7ff",
          fontSize: 20,
        },
      },
      series: [
        {
          name: "工单数量",
          type: "bar",
          data: sortedDataRef.current,
          label: {
            show: true,
            position: "right",
            formatter: "{c}",
            color: "#fff",
            fontSize: 20,
          },
          itemStyle: {
            color: function (params) {
              const rank = params.dataIndex;
              if (rank < 3) {
                return ["#24d39a", "#24bbec", "#ffc640"][rank];
              } else {
                const colorStops = [
                  { offset: 0, color: "#1d6fa0" },
                  { offset: 1, color: "#1976D2" },
                ];
                return {
                  type: "linear",
                  x: 0,
                  y: 0,
                  x2: 1,
                  y2: 0,
                  colorStops: colorStops,
                };
              }
            },
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: "rgba(36, 187, 236, 0.5)",
            },
          },
        },
      ],
      animation: true,
      animationDuration: 1000,
      animationEasing: "cubicInOut",
    };

    if (chartInstance.current) {
      chartInstance.current.setOption(option);
    }
  };

  const setupAutoScroll = () => {
    const scrollChart = () => {
      const visibleItems = 8;
      if (sortedBureausRef.current.length <= visibleItems) return;

      startIndexRef.current = (startIndexRef.current + 1) % (sortedBureausRef.current.length - visibleItems + 1);

      if (chartInstance.current) {
        chartInstance.current.setOption({
          yAxis: {
            data: sortedBureausRef.current.slice(startIndexRef.current, startIndexRef.current + visibleItems),
          },
          series: [
            {
              data: sortedDataRef.current.slice(startIndexRef.current, startIndexRef.current + visibleItems),
            },
          ],
        });
      }
    };

    scrollIntervalRef.current = setInterval(scrollChart, 5000);
  };

  return (
    <div className="incident-area-container">
      <div 
        ref={chartRef} 
        id="incident-area-chart" 
        style={{ width: '100%', height: '100%' }}
      ></div>
    </div>
  );
};

export default IncidentAreaStats;
